import requests
from bs4 import BeautifulSoup
import smtplib
from email.mime.text import MIMEText
from email.message import EmailMessage
import schedule
import time
from datetime import datetime
from jiangxishuiwen import crawl2 as j_crawl
from dajiangdahe import crawl2 as d_crawl
import os
import sys
import ssl
import yaml
# 爬取数据的函数
def fetch_data():
    Base_DIR = os.path.dirname(os.path.realpath(sys.argv[0]))
    print(f"当前路径:{Base_DIR}")
    # config_file = 'config.ini'
    # folder = folder_path
    if not os.path.exists(f"{Base_DIR}/Temp"):  #判断是否存在文件夹如果不存在则创建为文件夹
        os.makedirs(f"{Base_DIR}/Temp")
        print("创建临时文件夹")

    if not os.path.exists(f"{Base_DIR}/save"):
        os.makedirs(f"{Base_DIR}/save")
        print("创建文件保存路径")

    filename_jxsw, filename_pyh = j_crawl(f"{Base_DIR}/save")
    # filename_djdh = ""
    filename_djdh =  d_crawl(f"{Base_DIR}/save")
    return filename_jxsw, filename_pyh, filename_djdh

# 发送邮件的函数
def send_email(subject, file_list, recipient_list):
    
    sender_email = 'jzhouwang@163.com'
    sender_password = 'BLnm736uzrjztvY5'

    context = ssl.create_default_context()
    body = f"{subject}请查收！"
    msg = EmailMessage()
    msg['Subject'] = subject
    msg['From'] = sender_email
    msg['To'] = ', '.join(recipient_list)
    msg.set_content(body) 

    # 发送多个附件
    for file in file_list:
        with open(file, 'rb') as f:
            datatimenow = datetime.now().strftime("%Y-%m-%d_%H:%M:%S")
            file_data = f.read()
            file_name = os.path.basename(file)
            file_name = file_name.split(".")[0] + f"-{datatimenow}.xlsx"
            msg.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=file_name)

    with smtplib.SMTP_SSL('smtp.163.com', 465, context=context) as server:  # 替换为你的 SMTP 服务器
        # server.starttls()
        server.login(sender_email, sender_password)
        server.send_message(msg)

# 定时任务
def job():
    current_time = datetime.now()
    formatted_time = current_time.strftime("%Y-%m-%d_%H:%M:%S")
    print(f"开始执行任务， 当前时间：{formatted_time}")
    Base_DIR = os.path.dirname(os.path.realpath(sys.argv[0]))
    filename_jxsw, filename_pyh, filename_djdh = fetch_data()
    file_list = [f'{Base_DIR}/save/{filename_jxsw}',
                f'{Base_DIR}/save/{filename_pyh}',
                f'{Base_DIR}/save/{filename_djdh}']
    
    subject = f'{formatted_time}水文数据'

    with open('conf.yaml', 'r', encoding='utf-8') as file:
        data = yaml.safe_load(file)
    recipient_list = data['rec_email']
    # with open("./rec.txt", 'r', encoding='utf-8') as file:
    #     recipient_list = [line.strip() for line in file.readlines()]
    # recipient_list = ['3454218761@qq.com', '1769926482@qq.com']  # 收件人列表
    send_email(subject, file_list[0:2], recipient_list)
    print("邮件已发送")
   
# 每小时执行一次爬取任务
# schedule.every(4).hours.do(job)
def main():
    with open('conf.yaml', 'r', encoding='utf-8') as file:
        data = yaml.safe_load(file)
    schedule.clear()
    schedule.every(data["time_snap"]).hours.do(job)
    # schedule.every(data["time_snap"]).seconds.do(job)
    while True:
        schedule.run_pending()


if __name__ == '__main__':
    main()
    
